//
//  DXdjsView.m
//  抢购倒计时
//
//  Created by Elephant on 15/11/24.
//  Copyright © 2015年 RDX. All rights reserved.
//

#import "DXdjsView.h"

@implementation DXdjs


#pragma mark*****************************

-(instancetype)initWithCountdownTime:(NSString *)currentTime
{
    self = [super init];
    if (self) {
        [self countdownTime:[currentTime intValue]];
    }
    return self;
}

+(instancetype)dlsWithCountdownTime:(NSString *)currentTime
{
    return [[self alloc]initWithCountdownTime:currentTime];
}

-(void)countdownTime:(int)time
{
    __block int timeOut  = time;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(self.timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);//每秒执行
    dispatch_source_set_event_handler(self.timer, ^{
        if (timeOut <= 0) { //倒计时结束,关闭
                        dispatch_source_cancel(self.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面显示
                NSArray *djsArr = [self TimeformatFromSeconds:timeOut];
                [self.delegate djsEnd:djsArr];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面显示
                NSArray *djsArr = [self TimeformatFromSeconds:timeOut];
                [self.delegate djsOngoing:djsArr];
                
            });
            timeOut -- ;
        }
    });
    dispatch_resume(self.timer);
}

-(NSArray *)TimeformatFromSeconds:(NSInteger)seconds
{
    //format of day
    NSString *str_day = [NSString stringWithFormat:@"%02d",seconds/(3600*24)];
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02d",(seconds/(3600))%24];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02d",(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02d",seconds%60];
    //format of time
    NSArray *format_time = [NSArray arrayWithObjects:str_day,str_hour,str_minute,str_second, nil];
    return format_time;
}

@end
